import { AnimationTask, createAnimationTask } from "@/lib/y-animation";

const transformCoordinate = (element: IElement, info: IMapInfo): IElement => {
  return {
    ...element,
    y: info.mapHeight - element.y + info.floorHeight - element.height,
  }
}

const setAttrList = (dom: HTMLElement, attrMap: { [key: string]: string }) => {
  Object.keys(attrMap).forEach(attr => {
    dom.setAttribute(attr, attrMap[attr]);
  })
}

const setStyle = (dom: HTMLElement, styleMap: { [key: string]: string }) => {
  Object.keys(styleMap).forEach(styleName => {
    dom.style[styleName as any] = styleMap[styleName];
  })
}

const useMap = (domID: string, mapHeight = 600, mapWidth = 1000, floorHeight = 0): IMap => {
  const animationTask = createAnimationTask();

  const info = {
    mapHeight,
    mapWidth,
    floorHeight
  };

  
  /**
   * create map
   */
  const mapDom = document.querySelector(`#${domID}`) as HTMLElement;
  const elementMap: { [key: string]: HTMLElement } = {};
  
  setStyle(mapDom, {
    width: `${mapWidth}px`,
    height: `${mapHeight}px`,
    border: '1px solid black',
  })

  const draw = (element: IElement) => {
    element = transformCoordinate(element, info);
    // todo
    let drawDom;
    if (elementMap[domID]) {
      drawDom = elementMap[domID];
    } else {
      drawDom = document.createElement('div');
      mapDom.appendChild(drawDom);
      setAttrList(drawDom, {
        id: element.domID,
      })
    }
    setStyle(drawDom, {
      width: `${element.width}px`,
      height: `${element.height}px`,
      transform: `translateX(${element.x}px) translateY(${element.y}px)`,
      backgroundColor: '#999' // test
    });
    drawDom.innerText = element.name || '';
  }

  return {
    info,
    draw,
    animationTask, 
  }
}

export default useMap;

export interface IMapInfo {
  floorHeight: number;
  mapHeight: number;
  mapWidth: number;
}

export interface IMap {
  info: IMapInfo;
  draw: (element: IElement) => void;
  animationTask: AnimationTask;
}

export interface IElement {
  domID: string;
  x: number;
  y: number;
  height: number;
  width: number;
  img?: string;
  name?: string;
}

